﻿using System;
using System.Text;
using System.Web;
using System.Web.Mvc;
using Matrix.Common.Utility;
using Matrix.MaKaYunShang.BLL;
using Matrix.MaKaYunShang.Model;
using Matrix.MaKaYunShang.Model.Dto;
using Matrix.MaKaYunShang.Model.Enum;

namespace Matrix.MaKaYunShang.McMagWeb.Controllers
{
    public class LoginController : BaseController
    {
        /// <summary>
        /// 微信授权
        /// </summary>
        public ActionResult WeChatAuthorize(string returnurl)
        {
            if (Request.Url == null)
            {
                Logger.Error(
                    "LoginController | WeChatAuthorize | The request url is null. ");
                throw new Exception(
                    "LoginController | WeChatAuthorize | The request url is null. ");
            }

            var projectInfo = GetCurrentMatrixCloudProjectInfo(MkysMcMagMcId);
            if (projectInfo == null || projectInfo.Id == 0)
            {
                Logger.Error(
                    "LoginController | WeChatAuthorize | Cannot get the project info from Matrix-Cloud-Center and db ");
                throw new Exception(
                    "LoginController | WeChatAuthorize | Cannot get the project info from Matrix-Cloud-Center and db ");
            }

            var wechatInfo = GetWechatInfoByProjectInfo(projectInfo.PjMcId, projectInfo.PjSecret);

            if (wechatInfo == null || wechatInfo.Id <= 0)
            {
                Logger.Error("LoginController | WeChatAuthorize | wechatInfo  Does not exist ");
                throw new Exception("LoginController | WeChatAuthorize | wechatInfo  Does not exist ");
            }

            var strCallBackUrl = "http://" + Request.Url.Host + "/Login/WeChatLogion?returnurl=" + HttpUtility.UrlEncode(returnurl);
            var strAuthInterfaceUrl = wechatInfo.AuthorizeUrl + "?callBackUrlEncode=" +
                                      System.Web.HttpContext.Current.Server.UrlEncode(strCallBackUrl);
            Response.Redirect(strAuthInterfaceUrl);
            return View();
        }

        public ActionResult WeChatLogion(string openId, string returnurl)
        {
            if (Request.Url == null)
            {
                Logger.Error(
                    "LoginController | WeChatLogion | The request url is null. ");
                throw new Exception(
                    "LoginController | WeChatLogion | The request url is null. ");
            }

            var projectInfo = GetCurrentMatrixCloudProjectInfo(MkysMcMagMcId);
            if (projectInfo == null || projectInfo.Id == 0)
            {
                Logger.Error(
                    "LoginController | WeChatLogion | Cannot get the project info from Matrix-Cloud-Center and db ");
                throw new Exception(
                    "LoginController | WeChatLogion | Cannot get the project info from Matrix-Cloud-Center and db ");
            }

            var wechatInfo = GetWechatInfoByProjectInfo(projectInfo.PjMcId, projectInfo.PjSecret);

            if (wechatInfo == null || wechatInfo.Id <= 0)
            {
                Logger.Error("LoginController | WeChatLogion | wechatInfo  Does not exist ");
                throw new Exception("LoginController | WeChatLogion | wechatInfo  Does not exist ");
            }

            var resultWechatUser = MatrixCloudCenterInterFuncBllobj.GetWechatUserInfo(openId, projectInfo.PjMcId,
                projectInfo.PjSecret);
            if (!resultWechatUser.Status || resultWechatUser.Data == null || resultWechatUser.Data.Id == 0)
            {
                Logger.Error("LoginController | WeChatLogion | Cannot get the wechat user info ");
                throw new Exception("LoginController | WeChatLogion | Cannot get the wechat user info ");
            }

            Logger.Info("LoginController | WeChatLogion |wechatUser.WiuId " + resultWechatUser.Data.WiuId);

            var mcAccounts = McAccountsBLL.Instance.GetModelWithRoleInfoByMxWechatInfoUserId(resultWechatUser.Data.WiuId);

            if (mcAccounts == null)
            {
                return RedirectToAction("Index", new { mxWechatInfoUserId = EncryptionLib.Encrypt(resultWechatUser.Data.WiuId.ToString()) });
            }

            if (mcAccounts.MxWechatInfoUserId != resultWechatUser.Data.WiuId)
            {
                Logger.Error("LoginController | WeChatLogion | 绑定微信号和登录微信号不一致,跳转登录页面");
                return RedirectToAction("Index", new { mxWechatInfoUserId = EncryptionLib.Encrypt("-1") });
            }
            mcAccounts.openId = openId;
            Session["McAccounts"] = mcAccounts;
            var userCookie = new HttpCookie("McAccounts");
            userCookie.Values["u"] = EncryptionLib.Encrypt(mcAccounts.UserName, Encoding.UTF8);
            userCookie.Values["p"] = mcAccounts.PasswordHash;
            Response.Cookies.Add(userCookie);
            McMagOperationHistoryBLL.Instance.Add(new McMagOperationHistory
            {
                AddTime = DateTime.Now,
                Action =
                    "[登录成功]:微信授权登录，MxWechatInfoUserId:" + resultWechatUser.Data.WiuId + "，McAccountsId:" +
                    mcAccounts.AccountId,
                ActionUrl = Request.RawUrl,
                IpAddress = GetIp(),
                OptAccountId = mcAccounts.AccountId
            });

            var menucookie = new HttpCookie("UserNavMenuCookie") { Expires = DateTime.Now.AddDays(-1) };
            Response.Cookies.Add(menucookie);
            if (!string.IsNullOrEmpty(returnurl))
            {
                Response.Redirect(returnurl);
                Response.End();
                return new EmptyResult();
            }
            else
            {
                if (mcAccounts.RoleId == (int)CommonEnum.McAccountRole.Boss)
                {
                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    return RedirectToAction("List", "Orders");
                }
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="mxWechatInfoUserId">此wechatUserId为数据库McAccounts表中MxWechatInfoUserId字段</param>
        /// <returns></returns>
        public ActionResult Index(string mxWechatInfoUserId)
        {
            var menucookie = new HttpCookie("UserNavMenuCookie") { Expires = DateTime.Now.AddDays(-1) };
            Response.Cookies.Add(menucookie);

            var userAgent = Request.UserAgent;
            if (!string.IsNullOrEmpty(userAgent) && userAgent.ToLower().Contains("micromessenger") && string.IsNullOrEmpty(mxWechatInfoUserId))
            {
                return Redirect("/Login/WeChatAuthorize?returnurl=" + HttpUtility.UrlEncode(Request["returnurl"]));
            }
            ViewBag.MxWechatInfoUserId = mxWechatInfoUserId ?? "";
            return View();
        }

        /// <summary>
        /// 登录验证
        /// </summary>
        /// <param name="userName">用户名</param>
        /// <param name="pwd">密码</param>
        /// <param name="w">mxWechatInfoUserId（加密）</param>
        [HttpPost]
        public ActionResult LoginValidate(string userName, string pwd, string w = null)
        {
            var result = new Result();
            var projectInfo = GetCurrentMatrixCloudProjectInfo(MkysMcMagMcId);
            if (projectInfo == null || projectInfo.Id == 0)
            {
                result.Status = false;
                result.Message = "项目资料错误";
                Logger.Error(
                    "LoginController | LoginValidate | Cannot get the project info from Matrix-Cloud-Center and db ");
                return Json(result);

            }

            var operatorId = 0;
            if (string.IsNullOrEmpty(userName) || string.IsNullOrEmpty(pwd) || userName.Length > 32 || pwd.Length > 32)
            {
                result.Status = false;
                result.Message = "请正确输入";
            }
            else
            {
                var model = McAccountsBLL.Instance.GetModelByLogin(userName.Trim(), EncryptionLib.Encrypt(pwd, Encoding.UTF8));
                if (model == null)
                {
                    result.Status = false;
                    result.Message = "账号或者密码错误";
                }
                else
                {
                    Session["McAccounts"] = model;
                    CurrentUser = System.Web.HttpContext.Current.Session["McAccounts"] as McAccountDto;
                    var userCookie = new HttpCookie("McAccounts");
                    userCookie.Values["u"] = EncryptionLib.Encrypt(model.UserName, Encoding.UTF8);
                    userCookie.Values["p"] = model.PasswordHash;
                    Response.Cookies.Add(userCookie);
                    result.Status = true;
                    operatorId = model.AccountId;
                    int mxWechatInfoUserId;
                    if (!string.IsNullOrEmpty(w) && int.TryParse(EncryptionLib.Decrypt(w), out mxWechatInfoUserId) &&
                        model.MxWechatInfoUserId <= 0 && mxWechatInfoUserId > 0)
                    {
                        var temp = McAccountsBLL.Instance.GetModel(model.AccountId);
                        if (temp != null)
                        {
                            var shop = ShopsBLL.Instance.GetModel(temp.ShopId);
                            if (shop != null && shop.IsActive == false &&
                                CurrentUser.RoleId == (int) CommonEnum.McAccountRole.Boss &&
                                CurrentUser.AccountType == 1)
                            {
                                shop.IsActive = true;
                                ShopsBLL.Instance.Update(shop);
                            }
                            temp.MxWechatInfoUserId = mxWechatInfoUserId;
                            temp.UpdatedBy = model.AccountId;
                            temp.Updated = DateTime.Now;
                            temp.MxProjectInfoId = projectInfo.Id;
                            McAccountsBLL.Instance.Update(temp);
                        }
                    }

                    //如此账号未分配二维码，则分配一个未使用的二维码
                    if (model.MxWechatParamQrCodeId == 0)
                    {
                        var resultQrCode = MatrixCloudCenterInterFuncBllobj.GetUnBindParamQrCode(projectInfo.PjMcId,
                            projectInfo.PjSecret);
                        if (resultQrCode.Status && resultQrCode.Data != null && !resultQrCode.Data.IsBindWechatUser)
                        {
                            resultQrCode.Data.IsBindWechatUser = true;
                            resultQrCode.Data.ShopId = model.ShopId;

                            var resultSetQrCode =
                                MatrixCloudCenterInterFuncBllobj.SetBindParamQrCodeByWechatTicket(
                                    resultQrCode.Data.QrCodeTicket, model.ShopId, model.MxWechatInfoUserId,
                                    projectInfo.PjMcId, projectInfo.PjSecret);
                            if (resultSetQrCode.Status && resultSetQrCode.Data > 0)
                            {
                                var fullModel = McAccountsBLL.Instance.GetModel(model.AccountId);
                                if (fullModel != null)
                                {
                                    fullModel.MxWechatParamQrCodeId = resultQrCode.Data.Id;
                                    McAccountsBLL.Instance.Update(fullModel);
                                }
                            }
                        }
                    }
                }
                McMagOperationHistoryBLL.Instance.Add(new McMagOperationHistory
                {
                    AddTime = DateTime.Now,
                    Action = "[登录：" + (result.Status ? "成功" : "失败") + "]：账号：" + userName + "、密码：" +
                             (result.Status ? EncryptionLib.Encrypt(pwd, Encoding.UTF8) : pwd),
                    ActionUrl = Request.RawUrl,
                    IpAddress = GetIp(),
                    OptAccountId = operatorId
                });
            }
            return Json(result);
        }

        public ActionResult LoginOut()
        {
            Session["userModules" + CurrentUser.AccountId] = null;
            Session["McAccounts"] = null;
            var newcookie = new HttpCookie("McAccounts") { Expires = DateTime.Now.AddDays(-1) };
            Response.Cookies.Add(newcookie);

            var menucookie = new HttpCookie("UserNavMenuCookie") { Expires = DateTime.Now.AddDays(-1) };
            Response.Cookies.Add(menucookie);

            return RedirectToAction("Index", "Home");
        }

        [HttpPost]
        public JsonResult Logout()
        {
            Session["McAccounts"] = null;
            var newcookie = new HttpCookie("McAccounts") { Expires = DateTime.Now.AddDays(-1) };
            Response.Cookies.Add(newcookie);

            var menucookie = new HttpCookie("UserNavMenuCookie") { Expires = DateTime.Now.AddDays(-1) };
            Response.Cookies.Add(menucookie);

            return Json(true);
        }
    }
}